<template>
	<view class="sign-page">
		<view class="sign-board">
			<TnSignBoard ref="signBoardRef"/>
		</view>
		<view class="mt20">
			<tn-button shape="round" class="ml80" width="100%" height="90" font-size="34"
			           :custom-style="successBtnStyle" @click="confirmSign">
				确认签名
			</tn-button>
		</view>
		
		<!--合同canvas，用于合并合同和签名-->
		<canvas id="contract" canvas-id="contract" class="contract"
		        :style="`width:${canvasWidth}px;height:${canvasHeight}px`"></canvas>
	</view>
</template>

<script setup lang="ts">
import TnSignBoard from 'tnuiv3p-tn-sign-board/index.vue';
import type {TnSignBoardInstance} from 'tnuiv3p-tn-sign-board';

import {successBtnStyle} from "@/util/common";
import {ref} from "vue";

const signBoardRef = ref<TnSignBoardInstance>();
let imagePath = ref("");
let canvasWidth = ref(0);
let canvasHeight = ref(0);


const confirmSign = () => {
	uni.showLoading();
	signBoardRef.value?.save().then((res: any) => {
		imagePath.value = res;
		// 绘制合同
		let context = uni.createCanvasContext("contract", this);
		let imgSrc = "/static/img/contractImg.jpg";
		// 获取图片信息、宽高
		uni.getImageInfo({
			src: imgSrc,
			success: (img) => {
				canvasWidth.value = img.width;
				canvasHeight.value = img.height;
				context.drawImage(imgSrc, 0, 0);
				context.drawImage(imagePath.value, 470, canvasHeight.value - 330, 200, 200);
				context.draw();
				setTimeout(() => {
					// 生成一个本地临时图片
					uni.canvasToTempFilePath({
						canvasId: "contract",
						x: 0,
						y: 0,
						width: canvasWidth.value,
						height: canvasHeight.value,
						success: (res) => {
							console.log(res.tempFilePath);
							let fileName = `${(Math.random() * 1000000000).toFixed(0)}.png`;
							uniCloud.uploadFile({
								filePath: res.tempFilePath,
								cloudPath: fileName,
								cloudPathAsRealPath: true,
								success(result) {
									uni.setStorageSync("contractImgFileName", result.fileID);
									uni.hideLoading();
									uni.showToast({
										title: "签名成功",
										icon: "none"
									});
									uni.setStorageSync("isSign", "1");
									setTimeout(() => {
										uni.reLaunch({
											url: "/pages/index/questionnaireList"
										});
									}, 1500);
								},
								fail(result) {
									uni.showToast({
										title: "签名图片上传失败",
										icon: "error"
									});
								},
							});
						}
					});
				}, 200);
			},
			fail(result) {
				console.log(result, "获取图片信息错误");
			},
		});
		
	});
};
</script>

<style lang="scss">
.sign-page {
	text-align: center;
	
	.sign-board {
		width: 100%;
		height: 500rpx;
		border: 1px solid #ececec;
	}
	
	.contract {
		opacity: 0;
	}
}
</style>
